using B.S.XZYData.Api.Read.Application.Command.WorkTask;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Linq;
using System.Text;

namespace B.S.XZYData.Api.Read.Application.Handler.WorkTask
{
    /// <summary>
    /// 查询任务处理器
    /// </summary>
    public class QueryWorkTaskHandler : IRequestHandler<QueryWorkTaskCommand, ApiResult<WorkTaskPageResult>>
    {
        private readonly IBaseRepository<Domain.ZSHH.Task> _taskRepo;
        private readonly IBaseRepository<Domain.ZSHH.Process> _processRepo;
        private readonly IBaseRepository<Domain.RBAC.RoleModel> _roleRepo;
        private readonly IBaseRepository<Domain.ZSH.Defective> _defectiveRepo;
        private readonly ILogger<QueryWorkTaskHandler> _logger;

        public QueryWorkTaskHandler(
            IBaseRepository<Domain.ZSHH.Task> taskRepo,
            IBaseRepository<Domain.ZSHH.Process> processRepo,
            IBaseRepository<Domain.RBAC.RoleModel> roleRepo,
            IBaseRepository<Domain.ZSH.Defective> defectiveRepo,
            ILogger<QueryWorkTaskHandler> logger)
        {
            _taskRepo = taskRepo;
            _processRepo = processRepo;
            _roleRepo = roleRepo;
            _defectiveRepo = defectiveRepo;
            _logger = logger;
        }

        public async Task<ApiResult<WorkTaskPageResult>> Handle(QueryWorkTaskCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<WorkTaskPageResult>();
            try
            {
                // 构建基础查询
                var query = _taskRepo.GetAll()
                    .Where(x => !x.IsDeleted);

                // 应用筛选条件
                query = ApplyFilters(query, request);

                // 应用排序
                query = ApplySorting(query, request.SortField, request.SortDirection);

                // 获取总数
                var totalCount = await query.CountAsync();

                // 分页查询
                var taskList = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 获取工序信息
                var processIds = taskList.Select(x => x.ProcessId).Distinct().ToList();
                var processList = _processRepo.GetAll()
                    .Where(x => !x.IsDeleted && processIds.Contains(x.Id))
                    .ToList();

                // 转换为DTO
                var taskDtoList = taskList.Select(task =>
                {
                    var process = processList.FirstOrDefault(p => p.Id == task.ProcessId);
                    return new WorkTaskDto
                    {
                        Id = task.Id,
                        ProcessId = task.ProcessId,
                        ProcessName = process?.ProcessName,
                        ProcessNumber = process?.ProcessNumber,
                        ReportingPermissions = ConvertReportingPermissionsToNames(process?.ReportingPermissions),
                        ReportingRatio = process?.ReportingRatio,
                        DefectiveItemList = ConvertDefectiveItemListToNames(process?.DefectiveItemList),
                        AllocationList = ConvertAllocationListToNames(task.AllocationList),
                        PlannedStartTime = task.PlannedStartTime,
                        PlannedEndTime = task.PlannedEndTime,
                        PlannedQuantity = task.PlannedQuantity,
                        GoodQuantity = task.GoodQuantity,
                        DefectiveQuantity = task.DefectiveQuantity,
                        ActualStartTime = task.ActualStartTime,
                        ActualEndTime = task.ActualEndTime,
                        CreatorDate = task.CreatorDate,
                        Creator = task.Creator,
                        Updator = task.Updator
                    };
                }).ToList();

                var pageResult = new WorkTaskPageResult
                {
                    Data = taskDtoList,
                    Total = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize
                };

                res.Data = pageResult;
                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"查询任务异常：{ex.Message}");
                res.Msg = "查询任务异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }

        /// <summary>
        /// 应用筛选条件
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.Task> ApplyFilters(
            ISugarQueryable<Domain.ZSHH.Task> query,
            QueryWorkTaskCommand request)
        {
            var cc = 0;
            // 工序名称筛选
            if (!string.IsNullOrEmpty(request.ProcessName))
            {
                var processIds = _processRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.ProcessName.Contains(request.ProcessName))
                    .Select(x => x.Id)
                    .ToList();
                query = query.Where(x => processIds.Contains(x.ProcessId));
            }
            cc=query.Count();

            // 工序编号筛选
            if (!string.IsNullOrEmpty(request.ProcessNumber))
            {
                var processIds = _processRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.ProcessNumber.Contains(request.ProcessNumber))
                    .Select(x => x.Id)
                    .ToList();
                query = query.Where(x => processIds.Contains(x.ProcessId));
            }
            cc = query.Count();
            // 计划开始时间范围筛选
            if (request.PlannedStartTimeStart.HasValue)
            {
                query = query.Where(x => x.PlannedStartTime >= request.PlannedStartTimeStart.Value);
            }
            cc = query.Count();
            if (request.PlannedStartTimeEnd.HasValue)
            {
                query = query.Where(x => x.PlannedStartTime <= request.PlannedStartTimeEnd.Value);
            }
            cc = query.Count();
            // 计划结束时间范围筛选
            if (request.PlannedEndTimeStart.HasValue)
            {
                query = query.Where(x => x.PlannedEndTime >= request.PlannedEndTimeStart.Value);
            }
            cc = query.Count();
            if (request.PlannedEndTimeEnd.HasValue)
            {
                query = query.Where(x => x.PlannedEndTime <= request.PlannedEndTimeEnd.Value);
            }
            cc = query.Count();
            // 计划数范围筛选
            if (request.PlannedQuantityMin.HasValue)
            {
                query = query.Where(x => x.PlannedQuantity >= request.PlannedQuantityMin.Value);
            }
            cc = query.Count();
            if (request.PlannedQuantityMax.HasValue)
            {
                query = query.Where(x => x.PlannedQuantity <= request.PlannedQuantityMax.Value);
            }
            cc = query.Count();
            // 良品数范围筛选
            if (request.GoodQuantityMin.HasValue)
            {
                query = query.Where(x => x.GoodQuantity >= request.GoodQuantityMin.Value);
            }
            cc = query.Count();
            if (request.GoodQuantityMax.HasValue)
            {
                query = query.Where(x => x.GoodQuantity <= request.GoodQuantityMax.Value);
            }
            cc = query.Count();

            // 不良品数范围筛选
            if (request.DefectiveQuantityMin.HasValue)
            {
                query = query.Where(x => x.DefectiveQuantity >= request.DefectiveQuantityMin.Value);
            }
            cc = query.Count();
            if (request.DefectiveQuantityMax.HasValue)
            {
                query = query.Where(x => x.DefectiveQuantity <= request.DefectiveQuantityMax.Value);
            }
            cc = query.Count();
            // 实际开始时间范围筛选
            if (request.ActualStartTimeStart.HasValue)
            {
                query = query.Where(x => x.ActualStartTime >= request.ActualStartTimeStart.Value);
            }
            cc = query.Count();
            if (request.ActualStartTimeEnd.HasValue)
            {
                query = query.Where(x => x.ActualStartTime <= request.ActualStartTimeEnd.Value);
            }
            cc = query.Count();
            // 实际结束时间范围筛选
            if (request.ActualEndTimeStart.HasValue)
            {
                query = query.Where(x => x.ActualEndTime >= request.ActualEndTimeStart.Value);
            }
            cc = query.Count();
            if (request.ActualEndTimeEnd.HasValue)
            {
                query = query.Where(x => x.ActualEndTime <= request.ActualEndTimeEnd.Value);
            }
            cc = query.Count();
            // 创建时间范围筛选
            if (request.CreationTimeStart.HasValue)
            {
                query = query.Where(x => x.CreatorDate >= request.CreationTimeStart.Value);
            }
            cc = query.Count();
            if (request.CreationTimeEnd.HasValue)
            {
                query = query.Where(x => x.CreatorDate <= request.CreationTimeEnd.Value);
            }
            cc = query.Count();
            return query;
        }

        /// <summary>
        /// 转换报工权限ID为角色名称
        /// </summary>
        private string ConvertReportingPermissionsToNames(string? reportingPermissions)
        {
            if (string.IsNullOrEmpty(reportingPermissions))
                return string.Empty;

            try
            {
                var roleIds = reportingPermissions.Split(',', StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => s.Trim())
                    .Where(s => !string.IsNullOrEmpty(s))
                    .ToList();

                if (roleIds.Count == 0)
                    return string.Empty;

                var roleNames = new List<string>();
                foreach (var roleId in roleIds)
                {
                    if (int.TryParse(roleId, out int id))
                    {
                        if (id == 0)
                        {
                            roleNames.Add("所有人");
                        }
                        else
                        {
                            var role = _roleRepo.GetAll()
                                .Where(x => !x.IsDeleted && x.Id == id).ToList()
                                .FirstOrDefault();
                            if (role != null)
                            {
                                roleNames.Add(role.RoleName);
                            }
                            else
                            {
                                roleNames.Add(roleId);
                            }
                        }
                    }
                    else
                    {
                        roleNames.Add(roleId);
                    }
                }

                return string.Join(",", roleNames);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"转换报工权限失败：{ex.Message}");
                return reportingPermissions;
            }
        }

        /// <summary>
        /// 转换不良品项ID为编号|名称格式
        /// </summary>
        private string ConvertDefectiveItemListToNames(string? defectiveItemList)
        {
            if (string.IsNullOrEmpty(defectiveItemList))
                return string.Empty;

            try
            {
                var defectiveIds = defectiveItemList.Split(',', StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => s.Trim())
                    .Where(s => !string.IsNullOrEmpty(s))
                    .ToList();

                if (defectiveIds.Count == 0)
                    return string.Empty;

                var defectiveItems = new List<string>();
                foreach (var defectiveId in defectiveIds)
                {
                    if (int.TryParse(defectiveId, out int id))
                    {
                        var defective = _defectiveRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.Id == id).ToList()
                            .FirstOrDefault();
                        if (defective != null)
                        {
                            defectiveItems.Add($"{defective.DefectiveCode} | {defective.DefectiveName}");
                        }
                        else
                        {
                            defectiveItems.Add(defectiveId);
                        }
                    }
                    else
                    {
                        // 如果已经是"编号|名称"格式，直接使用
                        if (defectiveId.Contains("|"))
                        {
                            defectiveItems.Add(defectiveId);
                        }
                        else
                        {
                            defectiveItems.Add(defectiveId);
                        }
                    }
                }

                return string.Join(",", defectiveItems);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"转换不良品项失败：{ex.Message}");
                return defectiveItemList;
            }
        }

        /// <summary>
        /// 转换分配列表的角色ID为角色名称
        /// </summary>
        private string ConvertAllocationListToNames(string? allocationList)
        {
            if (string.IsNullOrEmpty(allocationList))
                return string.Empty;

            try
            {
                var roleIds = allocationList.Split(',', StringSplitOptions.RemoveEmptyEntries)
                    .Select(s => s.Trim())
                    .Where(s => !string.IsNullOrEmpty(s))
                    .ToList();

                if (roleIds.Count == 0)
                    return string.Empty;

                var roleNames = new List<string>();
                foreach (var roleId in roleIds)
                {
                    if (int.TryParse(roleId, out int id))
                    {
                        if (id == 0)
                        {
                            roleNames.Add("所有人");
                        }
                        else
                        {
                            var role = _roleRepo.GetAll()
                                .Where(x => !x.IsDeleted && x.Id == id).ToList()
                                .FirstOrDefault();
                            if (role != null)
                            {
                                roleNames.Add(role.RoleName);
                            }
                            else
                            {
                                roleNames.Add($"未知角色({roleId})");
                            }
                        }
                    }
                    else
                    {
                        // 如果不是数字，检查是否已经是角色名称
                        var existingRole = _roleRepo.GetAll()
                            .Where(x => !x.IsDeleted && x.RoleName == roleId).ToList()
                            .FirstOrDefault();
                        
                        if (existingRole != null)
                        {
                            // 如果已经是角色名称，直接使用
                            roleNames.Add(roleId);
                        }
                        else
                        {
                            // 如果既不是ID也不是角色名称，保留原值
                            roleNames.Add(roleId);
                        }
                    }
                }

                return string.Join(",", roleNames);
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"转换分配列表失败：{ex.Message}");
                return allocationList;
            }
        }

        /// <summary>
        /// 应用排序
        /// </summary>
        private ISugarQueryable<Domain.ZSHH.Task> ApplySorting(
            ISugarQueryable<Domain.ZSHH.Task> query,
            string sortField,
            string sortDirection)
        {
            switch (sortField.ToLower())
            {
                case "processname":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.ProcessId)
                        : query.OrderByDescending(x => x.ProcessId);

                case "plannedstarttime":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.PlannedStartTime)
                        : query.OrderByDescending(x => x.PlannedStartTime);

                case "plannedendtime":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.PlannedEndTime)
                        : query.OrderByDescending(x => x.PlannedEndTime);

                case "actualstarttime":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.ActualStartTime)
                        : query.OrderByDescending(x => x.ActualStartTime);

                case "actualendtime":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.ActualEndTime)
                        : query.OrderByDescending(x => x.ActualEndTime);

                case "creatordate":
                    return sortDirection.ToLower() == "asc"
                        ? query.OrderBy(x => x.CreatorDate)
                        : query.OrderByDescending(x => x.CreatorDate);

                default:
                    // 默认按Id倒序
                    return query.OrderByDescending(x => x.Id);
            }
        }
    }
} 